package iotwisp.school.api.interceptor;

import com.alibaba.fastjson.JSON;

import iotwisp.base.cqrs.BusinessException;
import iotwisp.base.cqrs.TraceHeader;
import iotwisp.base.jwt.JwtConfig;
import iotwisp.base.rest.JSONResultDTO;
import iotwisp.base.util.JwtUtil;
import iotwisp.base.util.SpringContextUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class LoginCheckInterceptor extends HandlerInterceptorAdapter {

	/**
	 *
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

//		Enumeration headerNames = request.getHeaderNames();
//		while (headerNames.hasMoreElements()) {
//			String key = (String) headerNames.nextElement();
//			String value = request.getHeader(key);
//			System.out.println("key:"+key);
//			System.out.println("value:"+value);
//		}

		log.info("开始拦截验证登录 {}", request.getRequestURI());
//		if (request.getRequestURI().indexOf("/api/org/admin/login") > -1 || request.getRequestURI().indexOf("/api/org/admin/authority/query") > -1 || request.getRequestURI().indexOf("/api/org/api_operate/query") > -1) {
//			return true;
//		}
		String jwt = request.getHeader("access-token");
		if (StringUtils.isBlank(jwt)) {
			createFailResult(response, BusinessException.NO_LOGIN, "未登录");
			log.info("未登录，不允许访问 {}", request.getRequestURI());
			return false;
		}

		log.info("context:" + SpringContextUtil.getApplicationContext());
		// 从配置中获取secret
		JwtConfig jwtConfig = (JwtConfig) SpringContextUtil.getBean("jwtConfig");

		String secret = jwtConfig.getSecret();
		log.info("jwt:{}", jwt);
		log.info("secret:{}", secret);

		Claims claims = null;
		// 解析出jwt内容
		try {
			claims = JwtUtil.parseJWT(jwt, secret);
		} catch (ExpiredJwtException e) {
			createFailResult(response, BusinessException.LOGIN_EXIPRE, "登录已过期，请重新登录");
			return false;
		} catch (Exception e) {
			createFailResult(response, BusinessException.SYSTEM_ERROR, "token无效");
			return false;
		}

		if (claims == null) {
			createFailResult(response, BusinessException.LOGIN_EXIPRE, "token无效，请重新登录");
			return false;
		}

		String loginSubjectId = claims.getSubject();
		log.info("loginSubjectId:{}", loginSubjectId);

		TraceHeader header = new TraceHeader();
		header.setCurrentUserId(loginSubjectId);
		header.setClientId((String) claims.get("clientId"));
		header.setClientType((String) claims.get("clientType"));
		header.setCurrentUserName((String) claims.get("loginName"));
		header.setClientIp((String) claims.get("clientIp"));

		request.setAttribute("traceHeader", header);
		return true;
	}

	private void createFailResult(HttpServletResponse response, String code, String msg) throws IOException {
		JSONResultDTO result = new JSONResultDTO();
		result.setCode(code);
		result.setMsg(msg);
		result.setData(null);
		response.setHeader("Content-type", "text/json;charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(JSON.toJSONString(result));
	}
}
